package com.hzy.fivepalace.wx.service;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;

import com.hzy.fivepalace.common.consts.RedisKeyConsts;
import com.hzy.fivepalace.common.service.redis.RedisCache;
import com.hzy.fivepalace.common.util.CharUtils;
import com.hzy.fivepalace.wx.dao.UserToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 维护用户token
 */
@Component
public class UserTokenManager {

    /**
     * token有效期天数
     */
    private final static int days = 60;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Resource
    private RedisCache redisCache;

    public Integer getUserId(String token) {
        if(StringUtils.isBlank(token)){
            return null;
        }
        UserToken userToken = redisCache.getCacheObject(token);
        if (userToken == null) {
            return null;
        }
        String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userToken.getUserId())});
        UserToken userKeyToken = redisCache.getCacheObject(key);
        if (userKeyToken == null) {
            return null;
        }
        if(!StringUtils.equals(userKeyToken.getToken(),userToken.getToken())){
            return null;
        }
        if (userToken.getExpireTime().isBefore(LocalDateTime.now())) {
            redisCache.deleteObject(token);
            redisCache.deleteObject(key);
            return null;
        } else {
            verifyToken(userToken, token);
        }
        return userToken.getUserId();
    }


    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param userToken
     * @param token
     */
    public void verifyToken(UserToken userToken, String token) {
        long expireTime = userToken.getExpireTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            LocalDateTime update = LocalDateTime.now();
            LocalDateTime expire = update.plusDays(days);
            userToken.setExpireTime(expire);
            userToken.setUpdateTime(update);
            redisCache.setCacheObject(token, userToken);
            String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userToken.getUserId())});
            redisCache.setCacheObject(key, userToken);
        }
    }

    public UserToken generateToken(Integer id, String sessionKey) {
        UserToken userToken;
        String token = CharUtils.getRandomString(32, id);
        LocalDateTime update = LocalDateTime.now();
        LocalDateTime expire = update.plusDays(days);
        userToken = new UserToken();
        userToken.setSessionKey(sessionKey);
        userToken.setToken(token);
        userToken.setUpdateTime(update);
        userToken.setExpireTime(expire);
        userToken.setUserId(id);
        redisCache.setCacheObject(token, userToken);
        String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(id)});
        redisCache.setCacheObject(key, userToken);
        return userToken;
    }


    public void removeToken(Integer userId) {
        String key = MessageFormat.format(RedisKeyConsts.WX_LOGIN_USER, new Object[]{String.valueOf(userId)});
        UserToken userToken = redisCache.getCacheObject(key);
        if (null != userToken) {
            String token = userToken.getToken();
            redisCache.deleteObject(key);
            redisCache.deleteObject(token);
        }
    }
}
